<?php
/*
Plugin Name: WPMU Catagorize Blogs
Plugin URI: http://aaron.jorb.in/wpmu-catagorize-blogs
Description: WordPressMU plugin to allow the Site Admin to put blogs in varius catagories
Version: 0.0
Author: Aaron Jorbin
Copyright:
    Copyright 2009 Aaron Jorbin

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/
if (isset($_GET['type']) && $_GET['type'] == 'css'){
	header("Content-type: text/css");


}
elseif (isset($_GET['type']) && $_GET['type'] == 'js'){
	header("Content-type: text/javascript");
?>
jQuery(document).ready(function($) {
		$('#mucbmain').tabs();
		$('.lastgroup').live('keyup',function() {
			var value = $('.lastgroup').val();
			if (value.length >= 3){
				$('.lastgroup').addClass("newgroup");
				$('.lastgroup').removeClass("lastgroup");
				$('.groups').append("<tr class='new'><td><input name='newgroup[]' class='lastgroup'/></td><td>0</td>");
			}
		});
	});

	<?php


}
else
{


function mucb_install_plugin(){
	if( is_site_admin() == false ) {
		wp_die( __('You do not have permission to access this page.') );
	}

	global $wpdb, $wp_queries;
	if (! get_site_option('mu_catagorize_blog_db_version') || get_site_option('mu_catagorize_blog_db_version') == false )
	{

		add_site_option('mu_catagorize_blog_db_version', '1');
		$table_name1 = $wpdb->base_prefix . "blog_tax";
		$table_name2 = $wpdb->base_prefix . "blog_tax_relationships";
		if($wpdb->get_var("SHOW TABLES LIKE '$table_name1'") != $table_name1 && $wpdb->get_var("SHOW TABLES LIKE '$table_name2'") != $table_name2 ) {

		$charset_collate = '';

// Declare these as global in case schema.php is included from a function.
		global $wpdb, $wp_queries;

			if ( $wpdb->has_cap( 'collation' ) ) {
	if ( ! empty($wpdb->charset) )
		$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
	if ( ! empty($wpdb->collate) )
		$charset_collate .= " COLLATE $wpdb->collate";
}

			$sql = "
				CREATE TABLE " . $table_name1 . " (
				  `tax_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
				  `tax_name` varchar(200) DEFAULT NULL,
				  `max_posts` tinyint(4) NOT NULL DEFAULT '0',
				UNIQUE KEY tax_id (tax_id)
				)$charset_collate;
				CREATE TABLE " . $table_name2 . " (
				relationship_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
				tax_id bigint(20) unsigned NOT NULL,
				blog_id bigint(20) unsigned NOT NULL,
				UNIQUE KEY relationship_id (relationship_id)
				)$charset_collate;
			";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
			dbDelta($sql);
			}
		return "Plugin Tables Installed.  Please click here to start catagorizing your blogs.";

		}
	elseif ( get_site_option('mu_catagorize_blog_db_version') == '1' )
	{
		$sql = "ALTER TABLE `".$wpdb->base_prefix."blog_tax` ADD `max_posts` TINYINT( 4 ) NOT NULL DEFAULT '0';";

		var_dump($sql);
		update_site_option('mu_catagorize_blog_db_version', '2');
	}
}

function mucb_add_submenu_page(){
	$mucbpage = add_submenu_page('wpmu-admin.php', 'Blog Taxonomy', 'Blog Taxonomy', 10, 'mucb_show_submenu_page', 'mucb_show_submenu_page');
	add_action('admin_print_scripts-' . $mucbpage, 'mucb_scripts');

}

function mucb_register_script(){
$src = WPMU_PLUGIN_URL . 'mu-catagorize-blogs.php?type=js';
	//wp_register_script('mucb_script', $src, array('jquery-ui-tabs') );

}

function mucb_scripts(){

	wp_enqueue_script('jquery-ui-tabs');

}

function mucb_show_submenu_page(){
	if( is_site_admin() == false ) {
		wp_die( __('You do not have permission to access this page.') );
	}
	global $wpdb;
echo '<div class="wrap">';
	$dbver = get_site_option('mu_catagorize_blog_db_version');
	if (!$dbver || $dbver != '3' ){
		echo mucb_install_plugin();
	}
		//Uncomment to reinstall the DB.
		//update_site_option('mu_catagorize_blog_db_version', false);
	if ( isset( $_POST['mucb_action'] ) )
		$action = strtolower( $_POST['mucb_action'] );
	else
		$action = 'show_submenu';
	switch ($action) {
		case 'update groups' :

			if (! wp_verify_nonce($_POST['_wpnonce'], 'mucb-groups') )
				wp_die('Security check'); ;
			$tax = $wpdb->base_prefix . "blog_tax";
			if (isset($_POST['newgroup'][0]) ){
				$sql = "INSERT INTO $tax (tax_id, tax_name) VALUES";
				$notfirst = false;
				foreach ($_POST['newgroup'] as $newgroup ){
					if (strlen($newgroup) >= 3){
						if ($notfirst)
							$sql .= ',';
						$sql .= "( null , \"$newgroup\")";
						$notfirst = true;
					}
				}
				$insert = $wpdb->query( $wpdb->prepare($sql.';') );
				foreach ($_POST['max'] as $key => $max){
					$max = (int) $max;
					$key = (int) $key;
					$sql = "UPDATE $tax SET max_posts='$max' where tax_id='$key'; ";
					$wpdb->query($wpdb->prepare($sql));
				}
				//var_dump($sql);
				//var_dump($insert);
			}
			echo '<div id="message" class="updated fade"><p>Groups Updated</p></div>';
			break;

		case 'update blogs' :
			if (! wp_verify_nonce($_POST['_wpnonce'], 'mucb-blogs') )
				wp_die('Security check'); ;

			$tax = $wpdb->base_prefix . "blog_tax";
			$groups = $wpdb->get_results("SELECT * FROM $tax WHERE 1;");
			$relationships = $wpdb->base_prefix . "blog_tax_relationships";
			$blogs = get_blog_list(0, 'all');
			$insert = "INSERT INTO $relationships (relationship_id , tax_id , blog_id ) VALUES";
			$first_new = false;
			$first_old = false;
			foreach($groups as $group){
				foreach($blogs as $blog){
					$new = 'new_'.$blog['blog_id'].'_'.$group->tax_id;
					if ($_POST[$new]){
						if ($first_new)
							$insert .= ',';
						$insert .='(null, "'.$group->tax_id.'", "'.$blog['blog_id'].'"  )';
						$first_new = true;
					}
					$set = 'set_'.$blog['blog_id'].'_'.$group->tax_id;
					if (! $_POST[$set] ){
						$term_id = $wpdb->get_var("SELECT relationship_id FROM $relationships WHERE tax_id = ".$group->tax_id." AND blog_id = ".$blog['blog_id']." LIMIT 1 ");
						$wpdb->query("DELETE FROM $relationships WHERE relationship_id = $term_id");
					}
				}
			}
			$sucinsert = $wpdb->query($insert.';');
			//var_dump ($sucinsert);
			//var_dump ($insert);
			echo '<div id="message" class="updated fade"><p>Blog Groups Updated</p></div>';
			break;

		default :
			echo "<h2>".'<div id="icon-edit" class="icon32"></div>'."This screen allows you to place your blogs into groups</h2>";
			break;

	}
	{
	$c_blogs = $wpdb->get_var("SELECT COUNT(blog_id) FROM $wpdb->blogs");
	$c_groups = $wpdb->get_var("SELECT COUNT(tax_id) FROM ". $wpdb->base_prefix . "blog_tax");
	$blog_text = sprintf( __ngettext( '%s blog', '%s blogs', $c_blogs ), number_format_i18n( $c_blogs ) );
	$groups_text = sprintf( __ngettext( '%s group', '%s groups', $c_groups ), number_format_i18n( $c_groups ) );
	$sentence = sprintf( __( 'You have %1$s in %2$s.' ), $blog_text, $groups_text );
}
	echo "
	<br />
	<div id='mucbmain' >
	<ul>
	<li><a href='#mucbgroupusers' class='button-secondary'>Show Users In Group</a></li>
	<li><br /></li>
	<li><a href='#mucbgroups' class='button-secondary' >Manage Groups</a></li>
	<li><br /></li>
	<li><a href='#mucbblogs' class='button-secondary'>Manage Blogs</a></li>
	</ul>
	<div id='mucbgroupusers'>
	" . mucb_show_users_in_groups() ."
	</div>

	<div id='mucbgroups'>

	". mucb_manage_groups() ."

	</div>
	<div id='mucbblogs'>
	".	mucb_manage_blogs() ."
	</div>


	</div>
	</div>
	";

	}

function mucb_manage_groups(){
	if( is_site_admin() == false ) {
		wp_die( __('You do not have permission to access this page.') );
	}
	global $wpdb;
	ob_start();
	echo "<h3>Use this Form to manage the groups</h3>";
	echo "
	<form method='post' >
	";
wp_nonce_field('mucb-groups');
	echo "<table class='widefat'>
<thead>
	<tr>
		<th>Group Name</th>
		<th>Group ID</th>
		<th>Count</th>
		<th>Max Posts To Show<br /> <span class='description'>0 means no limit</span></th>
	</tr>
</thead>
<tfoot>
    <tr>
	<th>Group Name</th>
	<th>Group ID</th>
	<th>Count</th>
	<th>Max Posts To Show</th>
    </tr>
</tfoot>
<tbody class='groups'>
";
$relationships = $wpdb->base_prefix . "blog_tax_relationships";
$tax = $wpdb->base_prefix . "blog_tax";
$sql = "SELECT `$tax`.`tax_name` ,`$tax`.`tax_id`, `$tax` . `max_posts` , COUNT(`$relationships`.`tax_id`) as count
FROM $tax
LEFT JOIN $relationships ON `$tax`.`tax_id` = `$relationships`.`tax_id`
GROUP BY `$relationships`.`tax_id` ;";
$groups = $wpdb->get_results($sql);
foreach ($groups as $group){
	echo "<tr>
	<td>".$group->tax_name."</td>
	<td>".$group->tax_id."</td>
	<td>".$group->count."</td>
	<td><input name='max[{$group->tax_id}]' value='{$group->max_posts}' ></td>
	</tr>";
}
	echo "
	<tr class='new'>
		<td><input name='newgroup[]' class='lastgroup'/></td>
		<td></td>
		<td></td>
		<id></id>
	</tr>

	</tbody>
</table>

	<input class=’button-primary’ type='submit' name='mucb_action' value='Update Groups'>
	<input type='hidden' name='action' value='update' />
	</form>";

	$groups = ob_get_clean();
	return $groups;


}

function mucb_manage_blogs(){
	if( is_site_admin() == false ) {
		wp_die( __('You do not have permission to access this page.') );
	}
	global $wpdb;
	ob_start();

	$tax = $wpdb->base_prefix . "blog_tax";
	$groups = $wpdb->get_results("SELECT * FROM $tax WHERE 1;");
	$blogs = get_blog_list(0, 'all');
//	var_dump ($blogs);
	echo "<h3>Use this Form to manage the blogs</h3>";
	echo "<form method='post'>";
	wp_nonce_field('mucb-blogs');
echo "<table class='widefat'>
<thead>
	<tr>
		<th>Name</th>

		";
		foreach($groups as $group)
			echo "<th>".$group->tax_name."</th>";
		echo "
	</tr>
</thead>
<tfoot>
    <tr>
		<th>Name</th>
		";
		foreach($groups as $group)
			echo "<th>".$group->tax_name."</th>";
		echo "
    </tr>
</tfoot>
<tbody>
";
$relationships = $wpdb->base_prefix . "blog_tax_relationships";
foreach ($blogs as $blog){
	echo "<tr><td>".esc_url($blog['domain'])."</td>";
	foreach($groups as $group){
		$sql = 'SELECT relationship_id FROM '.$relationships.' WHERE tax_id = '.$group->tax_id.' AND blog_id = '.$blog['blog_id'].' ;';
		$set = $wpdb->get_var($sql);
		//var_dump($set);
		//var_dump($sql);
		if ( $set )
			echo "<td><input type='checkbox' name='set_".$blog['blog_id']."_".$group->tax_id."' value='".$blog['blog_id']."' checked='checked' ></td>";
		else
			echo "<td><input type='checkbox' name='new_".$blog['blog_id']."_".$group->tax_id."' value='".$blog['blog_id']."' ></td>";
	}
	echo "</tr>
	";

}

echo "
</tbody>
</table>



	<input type='submit' class=’button-primary’ name='mucb_action' value='Update Blogs'>
	<input type='hidden' name='action/' value='update' />
	</form>

";

	$blogs = ob_get_clean();
	return $blogs;


}

/* Get an array of all blog_ids in a group
 *
 * @param int $group_id ID of the Group
 * @return array $blogs all the blog_ids in selected group
 */
function mucb_get_group_blogs($group_id){
	global $wpdb;
	$relationships = $wpdb->base_prefix . "blog_tax_relationships";
	$group_id = (int) $group_id;
	$sql = "SELECT blog_id FROM $relationships WHERE tax_id = '$group_id'; ";
	$blogs = $wpdb->get_col( $wpdb->prepare($sql) );
	return $blogs;
}

/* Get an array of all blog_ids in not in a group
 *
 * @param int $group_id ID of the Group
 * @return array $not_in_group all the blog_ids not in selected group
 */
function mucb_get_exclude_group($group_id){
	global $wpdb;
	$group_id = (int) $group_id;
	$group = mucb_get_group_blogs($group_id);
	$blogs = get_blog_list(0, 'all');
	foreach ($blogs as $blog){
		if (! in_array($blog['blog_id'], $group) )
			$not_in_group[] = $blog['blog_id'];
	}
	return $not_in_group;
}

function mucb_get_users_with_blogs_in_group($group_id){
	global $wpdb;
	$group_id = (int) $group_id;
	$sql = 'SELECT ID FROM '.$wpdb->users.' WHERE 1 ;';
	$users = $wpdb->get_col($sql);
	$group_blogs = mucb_get_group_blogs($group_id);
	$users_in_group = array();
	foreach ($users as $user_id){
		foreach ($group_blogs as $blog_id){
			if ( is_user_member_of_blog($user_id, $blog_id) )
				if (! in_array($user_id, $users_in_group) )
					$users_in_group[] = $user_id;

		}
	}
	return $users_in_group;
}

function mucb_show_users_in_groups(){
	ob_start();
	global $wpdb;
	echo "<div><form method='post'>";
	echo "<select name='group_of_users'>";
	$tax = $wpdb->base_prefix . "blog_tax";
	$sql = "SELECT `$tax`.`tax_name` ,`$tax`.`tax_id` FROM $tax";
	$groups = $wpdb->get_results($sql);
	foreach ($groups as $group)
		echo '<option value="'.esc_attr($group->tax_id).'">'.$group->tax_name.'</option>';
	echo "</select>
	<input type='submit' class='button-primary' name='mucb_action' value='Get User List'>
	<input type='hidden' name='action' value='get_users_in_group' />
	";

	if (isset( $_POST['action'] ) && $_POST['action'] == 'get_users_in_group' ){
		$group_id = (int) $_POST['group_of_users'];
		$users = mucb_get_users_with_blogs_in_group($group_id);
		echo "<table class='widefat'>
			<thead>
				<tr>
					<th>User Name</th>
					<th>User Email</th>
				</tr>
			</thead>
			<tfoot>
				 <tr>
					<th>User Name</th>
					<th>User Email</th>
				</tr>
			</tfoot>";
		foreach ($users as $user_id){
			$userdata = get_userdata( $user_id);
			echo "<tr>
				<td>".$userdata->user_login."</td>
				<td>".$userdata->user_email."</td>
			</tr>";

		}
		echo "</tbody></table>";

	}
	echo "</div></div>";
	$user_table = ob_get_clean();
	return $user_table;
}

function mucb_get_blogs_groups($blog_id){
	global $wpdb;
	$relationships = $wpdb->base_prefix . "blog_tax_relationships";
	$sql = "SELECT tax_id FROM $relationships WHERE blog_id = '$blog_id';";
	$blogs = $wpdb->get_col($sql);
	return $blogs;
}

function mucb_front_blog_id(){
	return 1;
}

function mucb_add_post_to_most_recent_posts_in_groups($post_id){
	global $wpdb, $blog_id;
	$groups = mucb_get_blogs_groups($blog_id);
	$group_post = mucb_post_to_group_array($post_id, $blog_id);
	$group_post_name = $group_post['blog_id'].'-'.$group_post['post_id'];
	foreach ($groups as $group){
		$group_name = "mucb-group-$group";
		$group_array = 	get_site_option($group_name);
		if ( is_array($group_array) ){
			if (array_key_exists($group_post_name, $group_array) )
				unset($group_array[$group_post_name]);
			$group_array[$group_post_name] = $group_post;
		} else { // no array, so let's built one }
			$group_array = mucb_build_most_recent_post_array($group);
		}
		update_site_option($group_name, $group_array);
	}


}


function mucb_post_to_group_array($post_id, $blog_id){
	$post = get_post($post_id, $filter='display');
	$group_post['blog_id'] =  $blog_id;
	$group_post['post_id'] = $post_id;
	$group_post['content'] = ( strlen($post->post_excerpt) != 0 ) ? $post->post_excerpt : mucb_trim_excerpt($post->post_content ) ;
	$group_post['permalink'] = get_permalink($post_id);
	$group_post['title'] = $post->post_title;
	$group_post['post_date_gmt'] = $post->post_date_gmt;
	return $group_post;
}

function mucb_trim_excerpt($text){
	//$text = apply_filters('the_content', $text);
	$text = str_replace(']]>', ']]&gt;', $text);
	$text = strip_tags($text);
	$excerpt_length = 55;
	$excerpt_more = '...';
	$words = explode(' ', $text, $excerpt_length + 1);
	if (count($words) > $excerpt_length) {
	  array_pop($words);
	  $text = implode(' ', $words);
	  $text = $text . $excerpt_more;
	}

	return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);

}

function mucb_sort_group_posts_by_blog($x, $y){
	if ( $x['blog_id'] == $y['blog_id'] )
		return 0;
	else if ( $x['blog_id'] < $y['blog_id'] )
		return -1;
	else
		return 1;
}

function mucb_sort_group_posts_by_date($x, $y){
	if ( $x['post_date_gmt'] == $y['post_date_gmt'] )
		return 0;
	else if ( $x['post_date_gmt'] < $y['post_date_gmt'] )
		return -1;
	else
		return 1;
}


function mucb_build_most_recent_post_array($group_id){
	$blogs = mucb_get_group_blogs($group_id);
	foreach ($blogs as $blog){
// Switch to blog, get most recent post, add it to array
		switch_to_blog($blog);
		$posts = get_posts('numberposts=1&order=DESC&orderby=date');
		$group_post = mucb_post_to_group_array( $posts[0]->ID , $blog );
		$group_post_name = $group_post['blog_id'].'-'.$group_post['post_id'];
		$group_array[$group_post_name] = $group_post;
		restore_current_blog();
	}
	if (is_array($group_array) )
		usort ($group_array, 'mucb_sort_group_posts_by_date');
	return $group_array;

}

function mucb_most_recent_tax_register(){
	register_taxonomy( 'recent_group_original_blog_id', 'recent_group', array( 'hierarchical' => false, 'label' => false, 'query_var' => false, 'rewrite' => false ) );
}

function mucb_get_updated_group($goup_id, $start = 0, $quantity = 10 ){
	global $wpdb;
	$group = mucb_get_group_blogs($group_id);
	$thisgroup = false;
	foreach ($group as $blog){
		if ($thisgroup)
			$thisgroup = "'$blog'";
		else
			$thisgroup .= ", '$blog'";
	}
	return $wpdb->get_results( $wpdb->prepare("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE
		blog_id IN ($thisgroup) AND
		site_id = %d AND
		public = '1' AND
		archived = '0' AND
		mature = '0' AND
		spam = '0' AND
		deleted = '0' AND
		last_updated != '0000-00-00 00:00:00'
		ORDER BY last_updated DESC limit %d, %d", $wpdb->siteid, $start, $quantity ) , ARRAY_A );
}

function mucb_list_updated_blogs_in_group($goup_id, $start = 0, $quantity = 10){

$blogs = mucb_get_updated_group($goup_id, $start = 0, $quantity = 10);
	if( is_array( $blogs ) ) {
		echo "	<ul>	<strong>Updated Blogs</strong>";
		foreach( $blogs as $details ) {
		echo "<li><a href='http://". $details[ 'domain' ] . $details[ 'path' ]."'>".get_blog_option( $details[ 'blog_id' ], 'blogname' ) ."</a></li>";
	}
	echo "	</ul>";
	}
}

function mucb_get_most_recent_posts_in_group($group_id){
	$group_name = "mucb-group-$group_id";
	$group_array = 	get_site_option($group_name);

	if (is_array($group_array) )
		return $group_array;
	else
		return false;
}

function mucb_list_most_recent_posts_in_group($group_id, $return = false){

	$group_array = mucb_get_most_recent_posts_in_group($group_id);
	add_filter('the_excerpt', 'wp_trim_excerpt');
	//*
	if (! $group_array){
		$group_array =	mucb_build_most_recent_post_array($group_id);
		$group_name = "mucb-group-$group_id";
		update_site_option($group_name, $group_array);
	}
	if (is_array ($group_array) ){
		ob_start();
		echo "<ul class='mostrecentingroup'>\n";
		remove_shortcode('show_recent_in');
		foreach ($group_array as $post){
			echo '<li><a href="'.esc_url($post['permalink']) .'">'.$post['title'].'</a> at <a href="'.get_blog_option($post['blog_id'] ,'siteurl').'">'.get_blog_option($post['blog_id'] ,'blogname').'</a>'.do_shortcode(apply_filters('the_excerpt', $post['content']) ). "</li>\n";
		}
		add_shortcode('show_recent_in', 'mucb_show_recent_posts_in_group_shortcode');
		echo "</ul>";
	}
	else {
		$list = 'No Entries';
	}
	$list = ob_get_clean();
	if ($return)
		return $list;
	else
		echo $list;
	//*/


	remove_filter('the_excerpt', 'wp_trim_excerpt');
}

function mucb_show_recent_posts_in_group_shortcode($atts){
	//remove_shortcode('show_recent_in');
	extract(shortcode_atts(array('group_id' => false), $atts));
	if (! $group_id ){
		return '';

	}

	else
		return	mucb_list_most_recent_posts_in_group( (int) $group_id, true);
	//add_shortcode('show_recent_in', 'mucb_show_recent_posts_in_group_shortcode');
}


add_shortcode('show_recent_in', 'mucb_show_recent_posts_in_group_shortcode');

add_action('publish_post', 'mucb_add_post_to_most_recent_posts_in_groups');
add_action('admin_menu', 'mucb_add_submenu_page');
add_action('admin_init', 'mucb_register_script');



}

?>
